<template>
  <ele-page>
    <FileSearch @search="reload" />
    <ele-card :body-style="{ paddingTop: '8px' }">
      <ele-pro-table
        ref="tableRef"
        v-model:selections="selections"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        highlight-current-row
        cache-key="systemFileTable"
      >
        <template #toolbar>
          <el-upload
            action=""
            :show-upload-list="false"
            :before-upload="onUpload"
            style="display: inline-block; vertical-align: middle"
          >
            <el-button type="primary" class="ele-btn-icon" :icon="Upload">
              上传
            </el-button>
          </el-upload>
          <el-button
            type="danger"
            class="ele-btn-icon"
            :icon="Delete"
            style="margin-left: 12px"
            @click="remove()"
          >
            删除
          </el-button>
        </template>
        <template #path="{ row }">
          <el-link
            type="primary"
            :href="row.url"
            target="_blank"
            underline="never"
          >
            {{ row.path }}
          </el-link>
        </template>
        <template #action="{ row }">
          <el-link
            type="primary"
            underline="never"
            :href="row.downloadUrl"
            target="_blank"
          >
            下载
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="danger" underline="never" @click="remove(row)">
            删除
          </el-link>
        </template>
      </ele-pro-table>
    </ele-card>
  </ele-page>
</template>

<script setup>
import { ref } from 'vue'
import { Delete, Upload } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus/es'
import { EleMessage } from 'ele-admin-plus/es'
import FileSearch from './components/file-search.vue'
import { pageFiles, removeFiles, uploadFile } from '@/api/system/file'

defineOptions({
  name: 'SystemFile',
})

/** 表格实例 */
const tableRef = ref(null)

/** 表格列配置 */
const columns = ref([
  {
    type: 'selection',
    columnKey: 'selection',
    width: 50,
    align: 'center',
    fixed: 'left',
  },
  {
    type: 'index',
    columnKey: 'index',
    width: 50,
    align: 'center',
    fixed: 'left',
  },
  {
    prop: 'name',
    label: '文件名称',
    sortable: 'custom',
    minWidth: 120,
  },
  {
    prop: 'path',
    label: '文件路径',
    sortable: 'custom',
    minWidth: 120,
    slot: 'path',
  },
  {
    prop: 'length',
    label: '文件大小',
    width: 120,
    align: 'center',
    sortable: 'custom',
    formatter: (row) => {
      if (row.length < 1024)
        return `${row.length}B`
      else if (row.length < 1024 * 1024)
        return `${(row.length / 1024).toFixed(1)}KB`
      else if (row.length < 1024 * 1024 * 1024)
        return `${(row.length / 1024 / 1024).toFixed(1)}M`
      else
        return `${(row.length / 1024 / 1024 / 1024).toFixed(1)}G`
    },
  },
  {
    prop: 'createNickname',
    label: '上传人',
    width: 120,
    align: 'center',
    sortable: 'custom',
  },
  {
    prop: 'createTime',
    label: '上传时间',
    width: 160,
    align: 'center',
    sortable: 'custom',
  },
  {
    columnKey: 'action',
    label: '操作',
    width: 120,
    align: 'center',
    slot: 'action',
  },
])

/** 表格选中数据 */
const selections = ref([])

/** 表格数据源 */
function datasource({ page, limit, where, orders }) {
  return pageFiles({ ...where, ...orders, page, limit })
}

/** 搜索 */
function reload(where) {
  selections.value = []
  tableRef.value?.reload?.({ page: 1, where })
}

/** 删除 */
function remove(row) {
  const rows = row == null ? selections.value : [row]
  if (!rows.length) {
    EleMessage.error('请至少选择一条数据')
    return
  }
  ElMessageBox.confirm(
    `确定要删除“${rows.map(d => d.name).join(', ')}”吗?`,
    '系统提示',
    { type: 'warning', draggable: true },
  )
    .then(() => {
      const loading = EleMessage.loading('请求中..')
      removeFiles(rows.map(d => d.id))
        .then((msg) => {
          loading.close()
          EleMessage.success(msg)
          reload()
        })
        .catch((e) => {
          loading.close()
          EleMessage.error(e.message)
        })
    })
    .catch(() => {})
}

/** 上传 */
function onUpload(file) {
  if (file.size / 1024 / 1024 > 100) {
    EleMessage.error('大小不能超过 100MB')
    return false
  }
  const loading = EleMessage.loading({
    message: '上传中..',
    mask: true,
  })
  uploadFile(file)
    .then(() => {
      loading.close()
      EleMessage.success('上传成功')
      reload()
    })
    .catch((e) => {
      loading.close()
      EleMessage.error(e.message)
    })
  return false
}
</script>
